<template>
	<view class="approve">
		<view class="approve-form-box">
			<view class="form-radio-item">
				<view class="title">审批结果</view>
				<radio-group @change="radioChangeApproveFlag">
					<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in flagEntities" :key="item.id">
						<view>
							<radio :value="item.id" color="#3f8cf7" :checked="index === currentRadioFlag"
								style="transform: scale(0.7)" />
						</view>
						<view>{{ item.label }}</view>
					</label>
				</radio-group>
			</view>
			<view class="form-item">
				<view class="title">审批意见</view>
				<input class="uni-input" placeholder="备注" v-model="approveEntity.info" maxlength="20" />
			</view>
			<view class="form-radio-item" style="border-bottom: none;">
				<view class="title">签名</view>
				<view class="canvan-box">
					<canvas class="canvas" ref="refCanvas" canvas-id="canvas" @touchstart="touchstart"
						@touchmove="touchmove" @touchend="touchend" style="width: 100%;"></canvas>
					<view class="footer-btn">
						<a @click="finish">确定</a>
						<a @click="clear">清空</a>
					</view>
				</view>
			</view>
			<button type="primary" class="btn" @click="saveApprove">同意</button>
		</view>
	</view>
</template>

<script>
	import {
		api,
		post
	} from '@/util/api.js'
	import {
		pathToBase64,
		base64ToPath
	} from '@/util/util.js'
	export default {
		props: {
			flag: '', // 关联类型，1：合同，2：报销，3：报价；4：支付申请
			relationId: '', // 关联审批对象Id
		},
		data() {
			return {
				approveEntity: {
					result: 1,
					info: null
				},
				flagEntities: [{
						id: '0',
						label: '同意',
						checked: 'true',
					},
					{
						id: '1',
						label: '驳回'
					}
				],
				currentRadioFlag: 0, // 当前选择是否拿到/开具发票
				//绘图图像
				ctx: '',
				//路径点集合
				points: [],
				//签名图片
				SignatureImg: '',
				uploadUrl: 'http://manager.qy-zb.com', // 上传文件基URL
				width: 0, // 画布宽
				height: 0, // 画布高
			}
		},
		mounted() {
			// let canvas = document.querySelector('.canvas > canvas')
			// let ctx = canvas.getContext('2d')
			// this.ctx = canvas
			// this.width = ctx.canvas.clientWidth
			// this.height = ctx.canvas.clientHeight
		},
		created() {
			this.createCanvas()
			// 动态获取画布宽高
			// 调出签名图片回显

			const img = new Image();

			post(api.UserSingle, {
				id: uni.getStorageSync('userId')
			}).then(res => {
				let that = this
				console.log(res.data.signUrl)
				// uni.downloadFile({
				// 	url: '/api/file/2024-01-18/2121510d-fc9e-4d38-b759-6fa258acb712.png',
				// 	success: (downloadResult) => {
				// 		console.log('下载成功', downloadResult.tempFilePath)
				// 		pathToBase64(downloadResult.tempFilePath).then(base64 => {
				// 			console.log(base64)
				// 			var img = new Image();
				// 			img.src = base64;
				// 			img.onload = () => {
				// 				// 获取 Canvas 元素
				// 				// 将图片绘制到 Canvas 上
				// 				//canvas.drawImage(img, 0, 0, 290, 130);
				// 			}
				// 		})
				// 	},
				// 	fail: (err) => {
				// 		console.log('下载失败', err)
				// 	}
				// })


				// uni.getImageInfo({
				// 	src: res.data.signUrl,
				// 	success: function(info) {
				// 		console.log(info)
				// 		// 绘制图片到canvas

				// 		that.ctx.drawImage(info.path, 0, 0, that.width, that.height);
				// 		// that.ctx.draw(true); // 绘制完成
				// 	},
				// 	fail: function(error) {
				// 		console.error('加载图片失败:', error);
				// 	}
				// });
			})
		},
		methods: {
			createCanvas() {
				var imgDownloadNum = 0;
				var timeStamp = new Date()
				//创建绘图对象
				this.ctx = uni.createCanvasContext('canvas', this);
				//设置画笔样式
				this.ctx.lineWidth = 4;
				this.ctx.lineCap = 'round';
				this.ctx.lineJoin = 'round';
			},
			touchstart(e) {
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};
				this.points.push(startPoint);
				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
			},
			touchmove(e) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
				if (len >= 2) {
					this.draw(); //绘制路径
				}
			},
			touchend() {
				this.points = [];
			},
			draw() {
				let point1 = this.points[0];
				let point2 = this.points[1];
				this.points.shift();
				this.ctx.moveTo(point1.X, point1.Y);
				this.ctx.lineTo(point2.X, point2.Y);
				this.ctx.stroke();
				this.ctx.draw(true);
			},
			clear() {
				let that = this;
				uni.getSystemInfo({
					success: function(res) {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						that.ctx.clearRect(0, 0, canvasw, canvash);
						that.ctx.draw(true);
					}
				});
			},
			finish() {
				let userId = uni.getStorageSync('userId')
				if (userId == null || userId == '' || userId == undefined) {
					return uni.showToast({
						icon: 'none',
						title: '请先登录'
					})
				}
				let that = this;
				uni.canvasToTempFilePath({
					canvasId: 'canvas',
					success: function(res) {
						console.log(res.tempFilePath);
						// 上传该图片到个人中心即可
						uni.uploadFile({
							url: that.uploadUrl + api.UploadSign,
							filePath: res.tempFilePath,
							name: 'multipartFile',
							formData: {
								'id': userId,
							},
							// 成功函数
							success: (res) => {
								uni.showToast({
									icon: 'none',
									title: '签名更新成功'
								})
							},
							// 失败提示用户重新上传
							fail: error => {
								console.log('失败', error);
							}
						})
					}
				});
			},
			// radio单选
			radioChangeApproveFlag: function(evt) {
				for (let i = 0; i < this.flagEntities.length; i++) {
					if (this.flagEntities[i].id === evt.detail.value) {
						this.currentRadioFlag = i
						this.approveEntity.result = i + 1
						break
					}
				}
			},
			saveApprove() {
				if (this.approveEntity.result == undefined || this.approveEntity.result == null || this.approveEntity
					.result == '') {
					return uni.showToast({
						icon: 'none',
						title: '审批结果不能为空'
					})
				}
				let url = this.flag == 1 ? api.ApproveContract : (this.flag == 2 ? api.ApproveExpense : (this.flag == 3 ?
					api.ApproveQuote : api.ApprovePay))
				const relationVo = {
					id: this.relationId
				}
				const approveRecordVo = {}
				approveRecordVo.info = this.approveEntity.info
				approveRecordVo.result = this.approveEntity.result
				relationVo.approveRecordVo = approveRecordVo
				post(url, relationVo).then(res => {
					uni.$emit('closePopup')
				})
			}
		}
	}
</script>

<style>
	@import '../static/css/ApprovePopup.css';
</style>